const jwt = require('jsonwebtoken');
require('dotenv').config();

// 生成token
exports.generateToken = (userId, userType = 'user') => {
  return jwt.sign(
    { id: userId, userType },
    process.env.JWT_SECRET,
    { expiresIn: process.env.JWT_EXPIRES_IN }
  );
};

// 验证token
exports.verifyToken = (token) => {
  try {
    return jwt.verify(token, process.env.JWT_SECRET);
  } catch (error) {
    return null;
  }
};

// 认证中间件
exports.authMiddleware = (req, res, next) => {
  // 从请求头获取token
  const token = req.header('Authorization')?.replace('Bearer ', '');
  
  if (!token) {
    return res.status(401).json({ success: false, message: '未授权访问' });
  }
  
  try {
    const decoded = this.verifyToken(token);
    if (!decoded) {
      return res.status(401).json({ success: false, message: '无效的token' });
    }
    
    req.user = decoded; // 将用户信息存储在请求对象中
    next();
  } catch (error) {
    res.status(401).json({ success: false, message: 'token验证失败' });
  }
};